package com.itheima.train.manager.search.service;

import com.alibaba.fastjson.JSON;
import com.itheima.train.manager.domain.TbRidingPlanDate;
import com.itheima.train.manager.domain.User;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RidingPlanDateService {

    @Autowired
    private RestHighLevelClient restHighLevelClient ;

    @Autowired
    private StringRedisTemplate redisTemplate ;

    public List<TbRidingPlanDate> searchByCondition(TbRidingPlanDate tbRidingPlanDate) {

        // 创建List集合对象
        List<TbRidingPlanDate> queryResult = new ArrayList<>() ;

        try {

            // 使用java客户端进行数据的搜索
            SearchRequest searchRequest = new SearchRequest("riding_plan_date") ;

            // 创建BoolQueryBuilder
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            // 构建搜索条件
            if(tbRidingPlanDate.getStartStationName() != null && !"".equals(tbRidingPlanDate.getStartStationName())){
                boolQueryBuilder.must(QueryBuilders.matchQuery("startStationName" , tbRidingPlanDate.getStartStationName()).analyzer("ik_smart")) ;
            }

            if(tbRidingPlanDate.getReceiveStationName() != null && !"".equals(tbRidingPlanDate.getReceiveStationName())) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("receiveStationName" , tbRidingPlanDate.getReceiveStationName()).analyzer("ik_smart")) ;
            }

            if(null != tbRidingPlanDate.getTrainRidingDate() && !"".equals(tbRidingPlanDate.getTrainRidingDate()) ) {
                boolQueryBuilder.must(QueryBuilders.termQuery("trainRidingDate" , tbRidingPlanDate.getTrainRidingDate())) ;
            }

            if(null != tbRidingPlanDate.getTrainType() && !"".equals(tbRidingPlanDate.getTrainType())) {
                boolQueryBuilder.must(QueryBuilders.termQuery("trainType" , tbRidingPlanDate.getTrainType())) ;
            }

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().trackTotalHits(true) ;
            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.size(1000) ;
            searchRequest.source(searchSourceBuilder);      // 设置请求参数
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            // 从SearchResponse对象中获取搜索结果
            SearchHits searchHits = searchResponse.getHits();
            SearchHit[] hitsHits = searchHits.getHits();
            for(SearchHit searchHit : hitsHits) {
                String sourceAsString = searchHit.getSourceAsString();
                TbRidingPlanDate ridingPlanDate = JSON.parseObject(sourceAsString, TbRidingPlanDate.class);
                queryResult.add(ridingPlanDate) ;
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回
        return queryResult ;

    }

    // 根据id从索引库中进行数据的查询
    public TbRidingPlanDate queryById(TbRidingPlanDate tbRidingPlanDate) {

        try {

            // 创建GetRequest对象
            GetRequest getRequest = new GetRequest("riding_plan_date") ;
            getRequest.id(String.valueOf(tbRidingPlanDate.getId())) ;
            GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            String sourceAsString = getResponse.getSourceAsString();
            TbRidingPlanDate ridingPlanDate = JSON.parseObject(sourceAsString, TbRidingPlanDate.class);

            // 从Redis中查询用户数据
            String userInfo = redisTemplate.boundHashOps("train_manager:userInfo").get(tbRidingPlanDate.getUser().getId()).toString();
            User user = JSON.parseObject(userInfo , User.class) ;
            ridingPlanDate.setUser(user);

            // 返回
            return ridingPlanDate ;

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回
        return new TbRidingPlanDate();
    }
}
